package com.datastructure.queue;

public class CycleArrayQueue implements MyArrayQueue{
    int[] array;
    private final int maxSize;//队列容量
    private int front;
    private int rear;
    public CycleArrayQueue (int maxSize) {
        array = new  int[maxSize];
        this.maxSize = maxSize;
        front = 0;
        rear = 0;
    }

    //取出队头元素
    public int get() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空，无法取出");
        }
        int value = array[front];
        System.out.println("取出元素：" + value);
        front = (front + 1)%maxSize;
        return value;//front 所指的就是队头元素
    }

    //添加元素
    public void add(int num) {
        if (isFull()) {
            System.out.println("队列已满，无法添加 " + num);
            return;
        }
        array[rear] = num;//添加到 rear 所在位置，然后 rear+1
        rear = (rear + 1)%maxSize;
        System.out.println("成功添加元素：" + num);
    }

    //判断队列是否满了
    private boolean isFull() {
        return (rear + 1)%maxSize == front;
    }

    //队列是否为空
    public boolean isEmpty() {
        return rear == front;
    }

    public int size() {
        return (rear + maxSize -front)%maxSize;
    }
    //展示队列中的元素
    public void show() {
        if(isEmpty()) {
            System.out.println("队列为空");
            return;
        }
        System.out.print("当前队列为：");
        for (int i=front;i<front + size();++i) {
            System.out.print(array[i%maxSize] + " ");
        }
        System.out.println();
    }

    //显示队头元素，不取出
    public int peek() {
        if(isEmpty()) {
            throw new RuntimeException("队列为空，无队头");
        }
        System.out.println("当前队头为：" + array[front]);
        return array[front];
    }
}
